import { Controller, Get, Post, Body, Patch, Param, Delete, Req, Res } from '@nestjs/common';
import { MsgCodeService } from './msg-code.service';
import * as svgCaptcha from 'svg-captcha';

@Controller('code')
export class MsgCodeController {
  constructor(private readonly msgCodeService: MsgCodeService) { }

  // 每次热更新后都需要前端刷新，req.session.code才不会丢失
  @Get()
  getCode(@Req() req, @Res() res) {
    const captcha = svgCaptcha.create({
      size: 4,//生成几个验证码
      fontSize: 50, //文字大小
      width: 100,  //宽度
      height: 34,  //高度
      background: '#cc9966',  //背景颜色
    })
    // req.session.code = '1212' //存入session
    console.log(captcha.text);
    req.session.code = captcha.text.toLocaleLowerCase() //存入session
    res.type('image/svg+xml')
    res.send(captcha.data)

    return this.msgCodeService.getCode();
  }

  @Post('create')
  create(@Body() body: any, @Req() req) {
    console.log(req.session, body);
    if (req.session?.code?.toLocaleLowerCase() === body.code.toLocaleLowerCase()) {
      return { status: 200, msg: '验证码正确' }
    } else {
      return { status: 500, msg: '验证码错误' }
    }

  }

}
